/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.cgb.portal.facade;

import br.cgb.portal.entity.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author LUCAS
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {

    @PersistenceContext(unitName = "PortalCGBPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
    
    public User findUserPerEmail(String email) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<User> cq = cb.createQuery(User.class);
        Root<User> root = cq.from(User.class);
        cq.where(cb.equal(root.get("email"), email));
        try {
            return getEntityManager().createQuery(cq).getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
    
    public User findUserPerEmailValidated(String email) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<User> cq = cb.createQuery(User.class);
        Root<User> root = cq.from(User.class);
        Predicate predicate1 = cb.equal(root.get("email"), email);
        Predicate predicate2 = cb.equal(root.get("validated"), true);
        cq.where(predicate1, predicate2);
        try {
            return getEntityManager().createQuery(cq).getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
}
